package com.gitee.wsl.jvm.net.security.hash

import com.gitee.wsl.ext.string.encryptSHA256
import java.security.SecureRandom

data class SaltedHash(
    val hash: String,
    val salt: String
)

interface HashingService {
    fun generateSaltedHash(value: String, saltLength: Int = 32): SaltedHash
    fun verify(value: String, saltedHash: SaltedHash): Boolean
}

class SHA256HashingService: HashingService {
    @OptIn(ExperimentalStdlibApi::class)
    override fun generateSaltedHash(value: String, saltLength: Int): SaltedHash {
        val salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLength)
        val saltAsHex = salt.toHexString()
        val hash = "$saltAsHex$value".encryptSHA256()
        return SaltedHash(
            hash = hash,
            salt = saltAsHex
        )
    }

    override fun verify(value: String, saltedHash: SaltedHash): Boolean {
        val hash = "${saltedHash.salt}$value".encryptSHA256()
        return hash == saltedHash.hash
    }
}